/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.system.extend.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.auth.Auth;
import com.foreveross.bsl.auth.service.IdentityService;
import com.foreveross.bsl.common.utils.bean.BeanHelper;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.system.application.AccountApplication;
import com.foreveross.bsl.system.application.extend.AuthSettingApplication;
import com.foreveross.bsl.system.application.extend.vo.AuthSettingVO;
import com.foreveross.bsl.system.application.vo.AccountVO;
import com.foreveross.bsl.web.BaseController;

/**
 * @description
 * 
 * @author rening
 * @version v1.0
 * 
 * @2013-6-13
 * 
 */
@Controller
@RequestMapping("/system/authSetting")
public class AuthSettingController extends BaseController {

	@Inject
	private AuthSettingApplication authSettingApplication;

	@Inject
	private AccountApplication accountApplication;
	
	@Autowired
	private IdentityService identityService;

	@ResponseBody
	@RequestMapping("/add")
	public Map<String, String> add(AuthSettingVO authSetting) {
		Map<String, String> result = new HashMap<String, String>();
		authSettingApplication.saveEntity(authSetting);
		result.put("result", "success");
		return result;
	}
    
    /** 适配外部认证，c：app角色认证 b：后台登录认证
     * @param request
	 * @param authSetting
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Map<String, Object> saveAccount(HttpServletRequest request, AuthSettingVO authSetting) {
		
		Map<String, Object> result = new HashMap<String, Object>();
		String sessionKey = (String) request.getSession().getAttribute("sessionKey");
		Object obj = identityService.validateTicket(sessionKey);

		if(authSetting != null) {
			if (obj instanceof Auth) {
				Auth auth = (Auth) obj; 
				List<AccountVO> accList = this.accountApplication.getEntityByUserName(auth.getAccountUsername());
				if(accList != null && !accList.isEmpty()) {
					AccountVO vo = accList.get(0);
					if("c".equals(authSetting.getClientType())) { // c:app客户端登录扩展
						vo.setAuthType(authSetting.getAuthMethod()); // 系统或扩展
					} else { // b:后台管理员登录扩展
						vo.setAdminAuthType(authSetting.getAuthMethod());
					}
					this.accountApplication.updateEntity(vo.getId(), vo);
				}
			}
			if(!"d".equals(authSetting.getAuthMethod())) { // e：外部系统扩展 不等于d（系统默认）就是e
				if(StringUtils.isNotEmpty(authSetting.getId())) {
					AuthSettingVO entity = authSettingApplication.getEntity(authSetting.getId());
					entity.setProtocol(authSetting.getProtocol());
					entity.setIp(authSetting.getIp());
					entity.setDomain(authSetting.getDomain());
					entity.setUri(authSetting.getUri());
					entity.setPort(authSetting.getPort());
					authSetting = this.authSettingApplication.updateEntity(authSetting.getId(), entity);
				} else {
					authSetting.setId(null);
					authSetting = this.authSettingApplication.saveEntity(authSetting);
				}
			} else { // d:系统默认,有待完善
				// this.authSettingApplication.deleteEntity(authSetting.getId());
			}
			
		}
		result.put("result", true);
		return result;
	}

	@RequestMapping("/view")
	public String view(HttpServletRequest request, Model model) {
//		String sessionKey = (String) request.getSession().getAttribute(
//				"sessionKey");
//		Object obj = identityService.validateTicket(sessionKey);
//		if (obj instanceof Auth) {
//			Auth auth = (Auth) obj;
//			AuthSettingVO authSetting = null;
//			List<AuthSettingVO> list = authSettingApplication.getEntityByUserName(auth.getUsername());
//			if(list != null && !list.isEmpty()){
//				authSetting = list.get(0);
//			} else {
//				authSetting = new AuthSettingVO();
//			}
//
//			List<AccountVO> acclist = accountApplication.getEntityByUserName(auth.getUsername());
//			if(acclist != null && !acclist.isEmpty()){
//				authSetting.setAuthMethod(acclist.get(0).getAuthType());
//			}
//			model.addAttribute("authSetting", authSetting);
//		}
		return "setting/authSetting";
	}

	@ResponseBody
	@RequestMapping("/list")
	public Map<String, Object> list(HttpServletRequest request, Model model) {
		String sessionKey = (String) request.getSession().getAttribute(
				"sessionKey");
		Object obj = identityService.validateTicket(sessionKey);
		List<AuthSettingVO> list = new ArrayList<AuthSettingVO>(), reList = null;
		if (obj instanceof Auth) {
			Auth auth = (Auth) obj;
			AuthSettingVO authSetting = null;
			AccountVO accountVO = null;
			List<AccountVO> acclist = accountApplication.getEntityByUserName(auth.getAccountUsername());
			if(!acclist.isEmpty()){
				accountVO = acclist.get(0);
				
				authSetting = new AuthSettingVO();
				authSetting.setAuthMethod(accountVO.getAuthType());
				authSetting.setClientType("c");
				list.add(authSetting);
				
				authSetting = new AuthSettingVO();
				authSetting.setAuthMethod(accountVO.getAdminAuthType());
				authSetting.setClientType("b");
				list.add(authSetting);
			}
			reList = authSettingApplication.getEntityByUserName(auth.getAccountUsername());
			
			if(!reList.isEmpty()){
				for (AuthSettingVO vo : list) {
					for (AuthSettingVO asVO : reList) {
						if(vo.getClientType().equals(asVO.getClientType())){
							asVO.setAuthMethod(vo.getAuthMethod());
							try {
								BeanHelper.copyProperties(vo, asVO);
							} catch (Exception e) {
								throw new ApplicationException(e.getMessage());
							}
						}
					}
				}
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("data", list);
		return result;
	}
	/* (non-Javadoc)
	 * @see com.foreveross.bsl.web.BaseController#getModuleMenuName()
	 */
	@Override
	protected String getModuleMenuName() {
		return "系统设置";
	}

}